﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;

namespace MolyMade.Http.Utilities
{
    public static class Utilities
    {
        public static string UrlEncode(string s, Encoding encoding = null)
        {
            if (encoding == null)
            {
                encoding = Encoding.Default;
            }
            return HttpUtility.UrlEncode(s, encoding);
        }

        public static string UrlDecoding(string s, Encoding encoding = null)
        {
            if (encoding == null)
            {
                encoding = Encoding.Default;
            }
            return HttpUtility.UrlDecode(s, encoding);
        }

        public static string ConcatParameters(string url, IDictionary<string, string> parameters)
        {
            if (parameters == null)
            {
                return url;
            }
            return $"{url}?{string.Join("&", parameters.Keys.Select(k => $"{k}={parameters[k]}"))}";
        }

        public static string ConcatParameters(IDictionary<string, string> parameters)
        {

            return string.Join("&",parameters.Keys.Select(k=>$"{k} = {parameters[k]}"));
        }


        public static CookieCollection StringToCookieCollection(string cookie)
        {
            string[] filter = {"path", "expires", "domain"};
            if (cookie == null)
            {
                return null;
            }
            CookieCollection cookieCollection = new CookieCollection();
            string[] pairList = cookie.Split(new string[] { ",", ";" }, StringSplitOptions.RemoveEmptyEntries);
            foreach (string pair in pairList)
            {
                string itemcookie = pair.Replace("\r\n", string.Empty).Replace("\n", string.Empty);
                string[] cookiePair = itemcookie.Split('=');
                if(cookiePair.Length!=2) continue;
                if (filter.Contains(cookiePair[0].Trim().ToLower())) continue;
                cookieCollection.Add(new Cookie(cookiePair[0].Trim(),cookiePair[1].Trim()));
            }
            return cookieCollection;
        }

        public static string HttpCookieCollectionToString(HttpCookieCollection cookieCollection)
        {
            return string.Join(";", cookieCollection.AllKeys.Select(c=>$"{c}={cookieCollection[c].Value}"));
        }
    }
}
